<?php
class pwLetsManagerPluginMain extends MainPiwamPlugin
{
    /**
   * IMPLEMENTS PIWAM PLUGIN INTERFACE
   */
  public function getPluginName()
  {
    return 'pwLetsManagerPlugin';
  }
  public function getPluginDescription()
  {
    return 'Add lets managing functions';
  }
  public function pluginInstall()
  {
    
  }
  public function pluginNightTasksForAssociation(Association $association)
  {
    $this->asksExpiredForAssociation($association);
  }
  
  private function asksExpiredForAssociation(Association $asso)
  {
     
    $assoId = $asso->getId();
    $asks = LetsUserAskTable::getAsksExpired($assoId);
    $memberIdAssociation = LetsConfiguration::memberIdForAssociation($assoId);
    $nbDaysRemove = LetsConfiguration::nbDaysDeleteAskAfterMail($assoId);
     
    $nbExpiredMails =0;
    $nbAsksRemoved = 0;
     
    foreach($asks as $ask)
    {
      // notify user befaore delete
      if($ask->getAskBeforeDelete())
      {
        // expiration email has not sent
        if($ask->getDateMailExpiration() == null)
        {
          MailerFactory::loadTemplateAndSend(null,$ask->getUser(),LetsManagerEmails::KEY_ASK_EXPIRED_RENEW,array(
            'ask.name' => $ask->getName(),
            'ask.category' => $ask->getCategory()->getName(),
            'ask.delay_remove' => $nbDaysRemove,
          ));
          $nbExpiredMails++;
          $ask->setDateMailExpiration(date('Y-m-d'));
          $ask->save();
        }
        // we remove asks expired after 20 days
        else
        {
          $timeNow = time();
          $timeMail  = strtotime($ask->getDateMailExpiration());
          $nbDaysExpired = round(($timeNow - $timeMail)/(60*60*24));
          if($nbDaysExpired >= $nbDaysRemove)
          {
            $nbAsksRemoved++;
            $ask->delete();
          }
        }
      }
      // delete
      else{
        $nbAsksRemoved++;
        $ask->delete();
      }
    }
     
    $this->log(sprintf('%d emails have been sent (ask expired email)', $nbExpiredMails));

    $this->log(sprintf('%d asks expired has been removed', $nbAsksRemoved));
  }
}